package it.tcm.TeacherClassMate.action;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import it.tcm.TeacherClassMate.beans.SessionUser;
import it.tcm.TeacherClassMate.beans.TransactionBean;
import it.tcm.TeacherClassMate.facade.TransactionManageBase;
import it.tcm.TeacherClassMate.frontend.beans.TransactionFrontBean;
import it.tcm.TeacherClassMate.util.TransactionBeanComparatorDesc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class UserDataAction extends Action {

	// --------------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Methods


	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	@SuppressWarnings("unchecked")
	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		 logger.info("USER DATA ACTION");
		 SessionUser sessionUser = (SessionUser) request.getSession().getAttribute("sessionUser");
		 TransactionFrontBean fbean = new TransactionFrontBean();
		 TransactionManageBase tmanage = new TransactionManageBase();
		 List<TransactionBean> tlist = tmanage.getTransactionBeanByUser(sessionUser.getUserId());
		 logger.debug("tlist size " + tlist.size());
		 Integer numTotVerif = new Integer(0);
		 for (TransactionBean t: tlist) {
			 numTotVerif = numTotVerif + t.getBuyverif();
			 logger.debug("mnumToverif " + numTotVerif);
		 }
		 fbean.setNumTotVerif(numTotVerif);
		 fbean.setTlist(new ArrayList<TransactionBean>(tlist));
		 Collections.sort(tlist,new TransactionBeanComparatorDesc());
		 if (tlist != null && tlist.size() > 0) {
			 Date lastDateBuyVerif = tlist.get(0).getBuydate();
			 fbean.setLastDateBuyVerif(dateToString(lastDateBuyVerif));
		 } else  fbean.setLastDateBuyVerif("");
		 request.setAttribute("tranFBean", fbean);
		 request.setAttribute("resultList", fbean.getTlist());
		 return mapping.findForward("userdata"); 		 
	}
	
	private String dateToString(Date data) {
		String datastring = null;
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        datastring= df.format(data);
		return datastring;
	}
	
	
	
}